<?php
namespace Addons\WechatOpenPlatform\Services;
use Models\BaseModel as Model;
use Services\Service;
use Addons\QyWechat\Helper;

class Wxopenapi extends Service
{
	//跳转微信授权平台扫码
	public function rebind() { 
	  //未绑定或重新绑定  
		$admin = self::get_agent_openPlat();
		$wid = \Session::get('wid');
	  	$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	  	$pre_auth_code = self::get_pre_auth_code();
	  	$h = Helper::getInstance()->get_http_server_name();
		$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $confing->AppId . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=".$h."/Addons/WechatOpenPlatform/Admin/receiveTicke/call_back.html?wid={$wid}"."&auth_type=1";
		echo "<script>location.href='" . $url . "'</script>";
	}

	//获取总后台管理员的信息 
	public function get_agent_openPlat($wid=""){
		$uid = \Session::get('uid');
	    $user = (new Model('user'))->find(['id' => $uid]); 
	    if($user->agid){
	        $agency = (new Model('user_agency'))->find(['id' => $user->agid]);
	    }else{
	        $pubs = (new Model('pubs'))->find($wid);
	        $users = (new Model('user'))->find($pubs->uid);
	        $agency = (new Model('user_agency'))->find(['id' => $users->agid]);
	    }
	    return $agency;
	}

	public function get_component_access_token($wid="") {
	    if($wid){
	        $admin = self::get_agent_openPlat($wid);
	    }else{
	        $admin = self::get_agent_openPlat();
	    }
	  	$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	  	$cat = (new Model('component_verify_ticket'))->find(['app_id' => $confing->AppId]);
  		if (intval(strtotime($cat->create_time)) + 7000 > time()) {
      		//如果有未过期的ComponentAccessToken
      		return $cat->component_access_token;
    	}
	  	// 重新请求
	  	$ticket = (new Model('component_verify_ticket'))->find(['app_id' => $confing->AppId]);
	  	$body = \HttpCurl::post(
	    "https://api.weixin.qq.com/cgi-bin/component/api_component_token",
	    json_encode([
	      "component_appid"         => $confing->AppId,
	      "component_appsecret"     => $confing->AppSecret,
	      "component_verify_ticket" => $ticket->component_verify_ticket,
	    ])
	  );
	  $resp_arr = json_decode($body, 1);
	  if (array_key_exists('component_access_token', $resp_arr)) {
	    //请求component_access_token成功
	    $cat->component_access_token = $resp_arr['component_access_token'];
	    $cat->ttime = $resp_arr['expires_in'];
	    $cat->create_time = date('Y-m-d H:i:s', time());
	    $cat->save();
	    return $cat->component_access_token;
	  } else {
	    return false;
	  }
	}

	public function get_pre_auth_code() {
	  	$component_access_token = self::get_component_access_token();
	  	if (!$component_access_token) {
	    	return false;
	  	}
		$admin = self::get_agent_openPlat();
	  	$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
		$body = \HttpCurl::post("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" . $component_access_token,
		json_encode([
		    "component_appid" => $confing->AppId,
		])
		);
		$resp_arr = json_decode($body, 1);
		if (array_key_exists('pre_auth_code', $resp_arr)) {
		//成功获取
		return $resp_arr['pre_auth_code'];
		} else {
		//获取失败
		return false;
		}
	}


	public function get_authorizer_access_tokens($authorizer_appid,$wid = ""){
		if(!$wid){
			$wid = \Session::get('wid');//当前登录的用户id
		}
	  	$gzh_token = (new Model('qy_gzh_token'))->find(['wid' => $wid,'authorizer_appid'=>$authorizer_appid]);
		if(!$gzh_token->id){
			return "";
		}
	    //直接获取存储的 authorizer_access_token
	    if (intval(strtotime($gzh_token->token_create_time)) + 7000 < time()) {
	      	//当前存储的令牌已经失效
	      	//发起令牌刷新请求
	      	//获取cat令牌
	      	$component_access_token = self::get_component_access_token($wid);
	      	if (!$component_access_token) {
	        	return false;
	      	}
	      	$admin = self::get_agent_openPlat($wid);
	  		$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	      	//发起刷新请求
	      	$body = \HttpCurl::post(
	        	"https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" . $component_access_token,
	        	json_encode([
	         		"component_appid"          => $confing->AppId,
	          		"authorizer_appid"         => $gzh_token->authorizer_appid,
	          		"authorizer_refresh_token" => $gzh_token->authorizer_refresh_token,
	        	])
	      	);
	      	$resp_arr = json_decode($body, 1);
	      	if (array_key_exists('authorizer_access_token', $resp_arr)) {
	        	//成功获取
	        	$gzh_token->authorizer_access_token = $resp_arr["authorizer_access_token"];
	        	$gzh_token->authorizer_refresh_token = $resp_arr['authorizer_refresh_token'];
	        	$gzh_token->token_create_time = date("Y-m-d H:i:s",time());
	        	$gzh_token->save();
	    	    self::get_authorizer_info($gzh_token->authorizer_appid);
	        	return $gzh_token->authorizer_access_token;
	      	} else {
		        //获取失败
		        return error;
	      	}
	    }
    	//未失效
    	return $gzh_token->authorizer_access_token;
	  	
	}


	function get_authorizer_access_token($auth_code = null,$wid = null) {
	  //先查找当前登录的用户
		if(!$auth_code){
			return false;
		}
	  	
	  	//第一次授权，回调url中使用
	  	$component_access_token = self::get_component_access_token();
	  	if (!$component_access_token) {
	    	return false;
	  	}
	  	$admin = self::get_agent_openPlat();
  		$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	  	$body = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" . $component_access_token,
	    		json_encode([
	      		"component_appid"    => $confing->AppId,
	      		"authorization_code" => $auth_code,
	    	])
	  	);
	  	$resp_arr = json_decode($body, 1);
	  	if (array_key_exists('authorization_info', $resp_arr)) {
		    //成功获取
			$gzh_token = (new Model('qy_gzh_token'))->find(['wid' => $wid,'authorizer_appid'=> $resp_arr['authorization_info']['authorizer_appid']]);
		    $gzh_token->authorizer_access_token = $resp_arr['authorization_info']['authorizer_access_token'];//权限令牌
		    $gzh_token->authorizer_refresh_token = $resp_arr['authorization_info']['authorizer_refresh_token'];//刷新令牌
		    $gzh_token->authorizer_appid = $resp_arr['authorization_info']['authorizer_appid'];//授权方appid
		    $gzh_token->token_create_time = date('Y-m-d H:i:s', time());//令牌创建时间
		    $gzh_token->wid = $wid;
		    $gzh_token->save();
		    self::get_authorizer_info($gzh_token->authorizer_appid,$wid);
	    	return $gzh_token->authorizer_appid;
	  	} else {
	    	//获取失败
	    	return false;
	  	}

	}



	//获取当前用户的小程序基本信息
	public function get_authorizer_info($authorizer_appid,$wid=null) {
	  	//先查找当前登录的用户
	  	$wid = $wid?$wid:\Session::get('wid');//当前登录的用户id
	  	$gzh_token = (new Model('qy_gzh_token'))->find(['wid' => $wid,'authorizer_appid'=> $authorizer_appid]);
	  	$admin = self::get_agent_openPlat();//管理员（管理员配置）
  		$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	  	$component_access_token = self::get_component_access_token();//获取当前后台登陆着的用户的授权令牌
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" . $component_access_token,
	    	json_encode([
	      		"component_appid"  => $confing->AppId,
	      		"authorizer_appid" => $gzh_token->authorizer_appid,
	    	])
	  	);
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('authorizer_info', $resp_arr)) {
	    	//成功设置
	    	$gzh_token->message = json_encode($resp_arr);
	    	$gzh_token->save();
	    	return "";
	  	} else {
	    	//获取失败
	    	return false;
	  	}
	}

	//拉取所有已授权的帐号信息
	public function api_get_authorizer_list(){
	  	$admin = self::get_agent_openPlat();//管理员（管理员配置）
  		$confing = (new Model('wx_open_confing'))->find(['pid' => $admin->id]);
	  	$component_access_token = self::get_component_access_token();
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=" . $component_access_token,
	    	json_encode([
	      		"component_appid"  => $confing->AppId,
	      		"offset" => 0,
	      		"count" => 100,
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('total_count', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return false;
	  	}
	}

	//创建开放平台帐号并绑定公众号/小程序
	public function create($authorizer_appid){
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/open/create?access_token=" . $authorizer_access_token,
	    	json_encode([
	      		"appid"  => $authorizer_appid
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('open_appid', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return $resp_arr;
	  	}
	}


	//获取公众号/小程序所绑定的开放平台帐号
	public function get($authorizer_appid){
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/open/get?access_token=" . $authorizer_access_token,
	    	json_encode([
	      		"appid"  => $authorizer_appid
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('open_appid', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return $resp_arr;
	  	}
	}

	//将公众号/小程序绑定到开放平台帐号下
	public function bind($authorizer_appid){
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$open_appid = self::get($authorizer_appid);
	  	if(!$open_appid["open_appid"]){
	  		return $open_appid;
	  	}
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/open/bind?access_token=" . $authorizer_access_token,
	    	json_encode([
	      		"appid"  => $authorizer_appid,
	      		"open_appid"  => $open_appid["open_appid"],
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('open_appid', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return $resp_arr;
	  	}
	}

	//将公众号/小程序从开放平台帐号下解绑
	public function unbind($authorizer_appid){
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$open_appid = self::get($authorizer_appid);
	  	if(!$open_appid["open_appid"]){
	  		return $open_appid;
	  	}
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $authorizer_access_token,
	    	json_encode([
	      		"appid"  => $authorizer_appid,
	      		"open_appid"  => $open_appid["open_appid"],
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('open_appid', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return $resp_arr;
	  	}
	}

	//代公众号调用接口
	public function clear_quota($authorizer_appid){
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=" . $authorizer_access_token,
	    	json_encode([
	      		"appid"  => $authorizer_appid
	    	])
	  	);	
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('open_appid', $resp_arr)) {
	    	//成功设置
	    	return $resp_arr;
	  	} else {
	    	//获取失败
	    	return $resp_arr;
	  	}
	}

 
 
	//同步所有数据
	public function batchget_material($authorizer_appid){
		setApi();
	  	$wid = \Session::get('wid');//当前登录的用户id
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
		$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" .$authorizer_access_token,
	    	json_encode([
	      		"type"  => "news",
	      		"offset"  => 0,
	      		"count"  => 1,
	    	])
	  	);
	  	$resp_arr = json_decode($resp, 1);
	  	if (array_key_exists('total_count', $resp_arr)) {
	    	if($resp_arr["total_count"] == 0){
	    		return false;die;
	    	}
	    	$total_count = $resp_arr["total_count"];
	    	for ($i=0; $i < $total_count;) { 
	    			$respd = \HttpCurl::post(
	    			"https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" .$authorizer_access_token,
			    	json_encode([
			      		"type"  => "news",
			      		"offset"  => $i,
			      		"count"  => 20,
			    	])
			  	);	
			  	$arraus = json_decode($respd, 1);
			  	$resps[] = $arraus;
    			$i = $i+20;
    		}
    		foreach ($resps as $key => $value) {
    			foreach ($value["item"] as $item_key => $item_v) {
					$arrs[] = $item_v;
					$qy_article = (new Model("qy_article"))->find(["wid"=>$wid,"media_id"=>$item_v["media_id"]]);
					if(!$qy_article->id){
						$qy_article = new Model("qy_article");
					}
					$qy_article->title = $item_v["content"]["news_item"][0]["title"];
					$qy_article->thumb_media_id = $item_v["content"]["news_item"][0]["thumb_media_id"];
					$qy_article->show_cover_pic = $item_v["content"]["news_item"][0]["show_cover_pic"];
					$qy_article->author = $item_v["content"]["news_item"][0]["author"];
					$qy_article->digest = $item_v["content"]["news_item"][0]["digest"];
					$qy_article->url = $item_v["content"]["news_item"][0]["url"];
					$qy_article->thumb_url = $item_v["content"]["news_item"][0]["thumb_url"];
					$qy_article->content_source_url = $item_v["content"]["news_item"][0]["content_source_url"];
					$qy_article->update_time = date('Y-m-d H:i:s',$item_v["content"]["update_time"]);
					$qy_article->ctime = date('Y-m-d H:i:s',$item_v["content"]["create_time"]);
					if(!$qy_article->id){	
						$qy_article->media_id = $item_v["media_id"];
						$qy_article->wid = $wid;
						$qy_article->authorizer_appid = $authorizer_appid;
					}
					$qy_article->updates_time = date('Y-m-d H:i:s', time());
					$qy_article->save();
    			}
    		}
    		$gzh_token = (new Model('qy_gzh_token'))->find(['wid' => $wid,'authorizer_appid'=> $authorizer_appid]);
    		$gzh_token->update_time = date("Y-m-d H:i:s");
    		$gzh_token->save();
    		sendSuccess("同步成功");
	  	}
	  	sendError("同步失败");
	}

	//单个更新
	public function get_material($media_id,$authorizer_appid){
		setApi();
	  	$wid = \Session::get('wid');//当前登录的用户id
	  	$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid);
	  	$qy_article = (new Model("qy_article"))->find(["wid"=>$wid,"media_id"=>$media_id]);
		$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" .$authorizer_access_token,
	    	json_encode([
	      		"media_id"  => $media_id
	    	])
	  	);	
	  	$arr = json_decode($resp, 1);
		$qy_article->title = $arr["news_item"][0]["title"];
		$qy_article->thumb_media_id = $arr["news_item"][0]["thumb_media_id"];
		$qy_article->show_cover_pic = $arr["news_item"][0]["show_cover_pic"];
		$qy_article->author = $arr["news_item"][0]["author"];
		$qy_article->digest = $arr["news_item"][0]["digest"];
		$qy_article->url = $arr["news_item"][0]["url"];
		$qy_article->thumb_url = $arr["news_item"][0]["thumb_url"];
		$qy_article->content_source_url = $arr["news_item"][0]["content_source_url"];
		$qy_article->update_time = date('Y-m-d H:i:s',$arr["update_time"]);
		$qy_article->ctime = date('Y-m-d H:i:s',$arr["create_time"]);
		$qy_article->updates_time = date('Y-m-d H:i:s', time());
		if($qy_article->save()){
		    sendSuccess("同步成功");
		}else{
			sendError("同步失败");
		}	
	}
	//生成公众号二维码
	public function get_code($authorizer_appid,$text,$wid,$action_name){
		$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid,$wid);
		if($action_name == "QR_LIMIT_STR_SCENE"){
			$resp = \HttpCurl::post(
		    	"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" .$authorizer_access_token,
		    	json_encode([
		      		"action_name"	  => "QR_LIMIT_STR_SCENE",
		      		"action_info"=>[
		      			"scene"=>[
		      				"scene_str"=>$text
		      			]
		      		]	
		    	])
		  	);	
		}else{
			$resp = \HttpCurl::post(
		    	"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" .$authorizer_access_token,
		    	json_encode([
		      		"action_name"	  => "QR_LIMIT_SCENE",
		      		"action_info"=>[
		      			"scene"=>[
		      				"scene_id"=>$text
		      			]
		      		]	
		    	])
		  	);	
		}
	  	$arr = json_decode($resp,1);
	  	\Log::error(json_encode($arr,320));
	  	$qrUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($arr["ticket"]);//ticket记得进行UrlEncode
	  	return $qrUrl;
	}

	//获取uniqid
	public function uniqid($authorizer_appid,$openid,$wid){
		$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid,$wid);
	  	$resp = \HttpCurl::get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$authorizer_access_token."&openid=".$openid,array());	
	  	$arr = json_decode($resp,1);
	  	return $arr;
	}

	//公众号发送文字
	public function send($authorizer_appid,$touser,$wid,$content){
		$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid,$wid);
		$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" .$authorizer_access_token,
	    	json_encode([
	      		"touser"  => $touser,
	      		"msgtype"	  => "text",
	      		"text"=>[
	      			"content"=>$content
	      		]	
	    	],JSON_UNESCAPED_UNICODE)
	  	);	
	  	$arr = json_decode($resp,1);
	  	return $arr;
	}

	//公众号发送文字
	public function send_link($authorizer_appid,$touser,$wid,$data){
		$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid,$wid);
		$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" .$authorizer_access_token,
	    	json_encode([
	      		"touser"  => $touser,
	      		"msgtype" => "news",
	      		"news"=>[
	      			"articles"=>[
	      				[
	      					"title"=>$data["link_title"],
	      					"description"=>$data["link_desc"],
	      					"url"=>$data["url"],
	      					"picurl"=>$data["link_pic"]
	      				]
	      			]
	      		]	
	    	],JSON_UNESCAPED_UNICODE)
	  	);	
	  	$arr = json_decode($resp,1);
	  	return $arr;
	}


	//公众号发送图片
	public function send_image($authorizer_appid,$touser,$wid,$content){
		$authorizer_access_token = self::get_authorizer_access_tokens($authorizer_appid,$wid);
		$image = self::upload($authorizer_access_token,$content);
		$resp = \HttpCurl::post(
	    	"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" .$authorizer_access_token,
	    	json_encode([
	      		"touser"  => $touser,
	      		"msgtype"	  => "image",
	      		"image"=>[
	      			"media_id"=>$image["media_id"]
	      		]	
	    	],JSON_UNESCAPED_UNICODE)
	  	);	
	  	$arr = json_decode($resp,1);
	  	return $arr;
	}

	//获取media_id 
	public function upload($authorizer_access_token,$content){
		$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" .$authorizer_access_token.'&type=image';	
		if(class_exists('CURLFile')){
		    $data = ['media' => new \CURLFile($_SERVER['DOCUMENT_ROOT'].'/'.$content)];
		}else{
		    $data = ['media' => "@".$_SERVER['DOCUMENT_ROOT']."/".$content];
		}
	  	$res = self::curl_post($url,$data);
	  	$arr = json_decode($res,1);
	  	return $arr;
	} 

	function curl_post($url, $data = null){
     	//创建一个新cURL资源
     	$curl = curl_init();
     	//设置URL和相应的选项 
     	curl_setopt($curl, CURLOPT_URL, $url);
     	curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false);
     	if (!empty($data)){
      		curl_setopt($curl, CURLOPT_POST, 1);
      		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
     	}
     	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     	//执行curl，抓取URL并把它传递给浏览器
     	$output = curl_exec($curl);
     	//关闭cURL资源，并且释放系统资源
     	curl_close($curl);
     	return $output;
    }

}
?>